#include "rotatedevices.h"
#include "qmath.h"

RotateDevices::RotateDevices(QWidget *parent) : QWidget(parent)
{

}

int RotateDevices::get_Rotate_Angle() const
{
    return this->rotateAngle;
}

void RotateDevices::setPlatform_Angle(const int degree)
{
    rotateAngle=degree;
    update();
}

void RotateDevices::paintEvent(QPaintEvent*)
{
    int width = 300, height = 300;
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.translate(width / 2, height / 2);
    drawCircle(&painter);
    drawScale(&painter);
    drawScaleNum(&painter);
    drawPointer(&painter);
}

void RotateDevices::drawCircle(QPainter *painter)
{
    int radius=140;
    painter->save();
    painter->setPen(QPen(Qt::black, 2));
    painter->setBrush(Qt::white);
    painter->drawEllipse(-radius,-radius,radius*2,radius*2);
    painter->restore();
}

void RotateDevices::drawScale(QPainter *painter)
{
    int r=130,lscale=10,sscale=6,scaleInterval = 10;
    painter->save();
    for(int angle=0;angle<360;angle+=scaleInterval){
       qreal endX, endY;
       qreal startx= r*qCos(angle*(M_PI/180));
       qreal starty= r*qSin(angle*(M_PI/180));

       if(angle%30==0){
           painter->setPen(QPen(Qt::red, 2));
           endX = startx + lscale * qCos(angle * (M_PI / 180));
           endY = starty + lscale * qSin(angle * (M_PI / 180));
       }
       else{
           painter->setPen(QPen(Qt::black, 2));
           endX = startx + sscale * qCos(angle * (M_PI / 180));
           endY = starty + sscale * qSin(angle * (M_PI / 180));
       }
        painter->drawLine(QPointF(startx, starty), QPointF(endX, endY));
    }
    painter->restore();
}

void RotateDevices::drawScaleNum(QPainter *painter)
{
    painter->save();
    painter->setPen(QPen(Qt::red, 2));
    painter->setFont(QFont("Arial",10));
    QFontMetricsF qf = QFontMetricsF(painter->font());
    painter->rotate(90);
    for(int i=0;i<360;i+=30){
        QString degree=QString("%1").arg(i);
        painter->translate(120,0);
        int w=static_cast<int>(qf.width(degree));
        int h=static_cast<int>(qf.height());
        painter->rotate(-90-i);
        painter->drawText(-w/2,h/2-2,degree);
        painter->rotate(90+i);
        painter->translate(-120,0);
        painter->rotate(30);
    }
    painter->restore();
}

void RotateDevices::drawPointer(QPainter *painter)
{
    QPolygon indicator;
    int r = 120;
    painter->rotate(90);
    indicator.setPoints(3, 100, -5,100, 5, r-2 ,0);
    painter->save();
    painter->rotate(rotateAngle);
    QRadialGradient haloGradient(0, 0, 60, 0, 0);
    haloGradient.setColorAt(0, QColor(100, 100, 100));
    haloGradient.setColorAt(1, QColor(250, 50, 50));
    painter->setPen(QColor(250, 150, 150));
    painter->setBrush(haloGradient);
    painter->drawConvexPolygon(indicator);
    painter->restore();
}
